package com.shkmall.file.controller;

import com.shkmall.common.pojo.Result;
import com.shkmall.common.pojo.StatusCode;
import com.shkmall.file.util.FastDFSClient;
import com.shkmall.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        /*判断文件是否存在
        * 获取文件的完整名
        * 判断名字是否为空
        * 获取文件扩展名
        * 调用工具类封装
        * 上传文件
        *
        * 返回路径信息及文件名*/

        try {
            if(file == null){
                throw new RuntimeException("文件不能为空");
            }
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            if(StringUtils.isEmpty(filename)){
                throw new RuntimeException("文件名字不能为空");
            }
            String substring = filename.substring(filename.lastIndexOf(".") + 1);
            System.out.println(filename.lastIndexOf("."));
            FastDFSFile fastDFSFile = new FastDFSFile(filename, filename.getBytes(), substring);
            
            String[] upload = FastDFSClient.upload(fastDFSFile);
          String url =  FastDFSClient.getTrackerUrl()+upload[0]+"/"+upload[1];
          return new Result(true, StatusCode.OK,"文件上传成功",url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.ERROR,"文件上传失败");
    }
}
